<template>
  <view class="analytics">
    <view class="time-filter">
      <view class="filter-tabs">
        <text v-for="tab in timeTabs" :key="tab.value" class="filter-tab" :class="{ active: activeTab === tab.value }"
          @click="switchTab(tab.value)">
          {{ tab.label }}
        </text>
      </view>
    </view>

    <view class="overview-stats">
      <view class="stat-row">
        <view class="stat-item">
          <text class="stat-value">{{ overview.totalRevenue }}</text>
          <text class="stat-label">总收入</text>
          <text class="stat-change" :class="overview.revenueChange >= 0 ? 'positive' : 'negative'">
            {{ overview.revenueChange >= 0 ? '+' : '' }}{{ overview.revenueChange }}%
          </text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ overview.totalOrders }}</text>
          <text class="stat-label">订单数</text>
          <text class="stat-change" :class="overview.ordersChange >= 0 ? 'positive' : 'negative'">
            {{ overview.ordersChange >= 0 ? '+' : '' }}{{ overview.ordersChange }}%
          </text>
        </view>
      </view>

      <view class="stat-row">
        <view class="stat-item">
          <text class="stat-value">{{ overview.newUsers }}</text>
          <text class="stat-label">新用户</text>
          <text class="stat-change" :class="overview.usersChange >= 0 ? 'positive' : 'negative'">
            {{ overview.usersChange >= 0 ? '+' : '' }}{{ overview.usersChange }}%
          </text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ overview.adViews }}</text>
          <text class="stat-label">广告观看</text>
          <text class="stat-change" :class="overview.adViewsChange >= 0 ? 'positive' : 'negative'">
            {{ overview.adViewsChange >= 0 ? '+' : '' }}{{ overview.adViewsChange }}%
          </text>
        </view>
      </view>
    </view>

    <view class="chart-section">
      <text class="section-title">收入趋势</text>
      <view class="chart-container">
        <view class="chart-placeholder">
          <text class="chart-text">收入趋势图</text>
          <text class="chart-desc">{{ activeTabLabel }}数据展示</text>
        </view>
        <view class="trend-data">
          <view v-for="(item, index) in trendData" :key="index" class="trend-item">
            <text class="trend-date">{{ item.date }}</text>
            <view class="trend-bar" :style="{ width: (item.value / maxTrendValue * 100) + '%' }"></view>
            <text class="trend-value">¥{{ item.value }}</text>
          </view>
        </view>
      </view>
    </view>

    <view class="analytics-grid">
      <view class="analytics-card">
        <text class="card-title">广告数据</text>
        <view class="card-content">
          <view class="metric">
            <text class="metric-label">观看次数</text>
            <text class="metric-value">{{ adAnalytics.totalViews }}</text>
          </view>
          <view class="metric">
            <text class="metric-label">完成率</text>
            <text class="metric-value">{{ adAnalytics.completionRate }}%</text>
          </view>
          <view class="metric">
            <text class="metric-label">收益</text>
            <text class="metric-value">¥{{ adAnalytics.revenue }}</text>
          </view>
        </view>
      </view>

      <view class="analytics-card">
        <text class="card-title">积分数据</text>
        <view class="card-content">
          <view class="metric">
            <text class="metric-label">发放积分</text>
            <text class="metric-value">{{ pointsAnalytics.totalEarned }}</text>
          </view>
          <view class="metric">
            <text class="metric-label">消费积分</text>
            <text class="metric-value">{{ pointsAnalytics.totalSpent }}</text>
          </view>
          <view class="metric">
            <text class="metric-label">使用率</text>
            <text class="metric-value">{{ pointsAnalytics.usageRate }}%</text>
          </view>
        </view>
      </view>
    </view>

    <view class="top-products">
      <text class="section-title">热门产品</text>
      <view class="product-list">
        <view v-for="(product, index) in topProducts" :key="product.id" class="product-item">
          <view class="product-rank">{{ index + 1 }}</view>
          <view class="product-info">
            <text class="product-name">{{ product.name }}</text>
            <text class="product-sales">销量: {{ product.sales }}</text>
          </view>
          <text class="product-revenue">¥{{ product.revenue }}</text>
        </view>
      </view>
    </view>

    <view class="user-analysis">
      <text class="section-title">用户分析</text>
      <view class="analysis-grid">
        <view class="analysis-item">
          <text class="analysis-title">用户活跃度</text>
          <text class="analysis-value">{{ userAnalysis.activeRate }}%</text>
        </view>
        <view class="analysis-item">
          <text class="analysis-title">平均订单金额</text>
          <text class="analysis-value">¥{{ userAnalysis.avgOrderAmount }}</text>
        </view>
        <view class="analysis-item">
          <text class="analysis-title">用户留存率</text>
          <text class="analysis-value">{{ userAnalysis.retentionRate }}%</text>
        </view>
        <view class="analysis-item">
          <text class="analysis-title">积分使用率</text>
          <text class="analysis-value">{{ userAnalysis.pointsUsageRate }}%</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeTab: 'week',
      timeTabs: [
        { label: '今日', value: 'today' },
        { label: '本周', value: 'week' },
        { label: '本月', value: 'month' },
        { label: '本年', value: 'year' }
      ],
      overview: {
        totalRevenue: '0',
        totalOrders: '0',
        newUsers: '0',
        adViews: '0',
        revenueChange: 0,
        ordersChange: 0,
        usersChange: 0,
        adViewsChange: 0
      },
      topProducts: [],
      userAnalysis: {
        activeRate: '0',
        avgOrderAmount: '0',
        retentionRate: '0',
        pointsUsageRate: '0'
      },
      trendData: [],
      maxTrendValue: 0,
      adAnalytics: {
        totalViews: 0,
        completionRate: 0,
        revenue: 0
      },
      pointsAnalytics: {
        totalEarned: 0,
        totalSpent: 0,
        usageRate: 0
      }
    }
  },

  computed: {
    activeTabLabel() {
      const tab = this.timeTabs.find(t => t.value === this.activeTab)
      return tab ? tab.label : ''
    }
  },

  onLoad() {
    this.loadAnalyticsData()
  },

  methods: {
    switchTab(tab) {
      this.activeTab = tab
      this.loadAnalyticsData()
    },

    async loadAnalyticsData() {
      try {
        const token = uni.getStorageSync('token')
        if (!token) {
          uni.navigateTo({ url: '/pages/auth/login' })
          return
        }

        // 加载概览数据
        const overviewRes = await uni.request({
          url: `http://localhost:3000/api/analytics/overview?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (overviewRes.data.success) {
          this.overview = overviewRes.data.data
        }

        // 加载热门产品
        const productsRes = await uni.request({
          url: `http://localhost:3000/api/analytics/top-products?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (productsRes.data.success) {
          this.topProducts = productsRes.data.data || []
        }

        // 加载用户分析
        const userRes = await uni.request({
          url: `http://localhost:3000/api/analytics/user-analysis?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (userRes.data.success) {
          this.userAnalysis = userRes.data.data
        }

        // 加载趋势数据
        const trendRes = await uni.request({
          url: `http://localhost:3000/api/analytics/trends?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (trendRes.data.success) {
          this.trendData = trendRes.data.data || []
          this.maxTrendValue = Math.max(...this.trendData.map(item => item.value), 1)
        }

        // 加载广告数据
        const adRes = await uni.request({
          url: `http://localhost:3000/api/analytics/ads?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (adRes.data.success) {
          this.adAnalytics = adRes.data.data
        }

        // 加载积分数据
        const pointsRes = await uni.request({
          url: `http://localhost:3000/api/analytics/points?period=${this.activeTab}`,
          method: 'GET',
          header: {
            'Authorization': `Bearer ${token}`
          }
        })

        if (pointsRes.data.success) {
          this.pointsAnalytics = pointsRes.data.data
        }

      } catch (error) {
        console.error('加载分析数据失败:', error)
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style scoped>
.analytics {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.header {
  text-align: center;
  margin-bottom: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.time-filter {
  margin-bottom: 30rpx;
}

.filter-tabs {
  display: flex;
  background: white;
  border-radius: 12rpx;
  padding: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.filter-tab {
  flex: 1;
  text-align: center;
  padding: 16rpx;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #666;
  transition: all 0.3s;
}

.filter-tab.active {
  background-color: #007bff;
  color: white;
}

.overview-stats {
  margin-bottom: 30rpx;
}

.stat-row {
  display: flex;
  gap: 20rpx;
  margin-bottom: 20rpx;
}

.stat-item {
  flex: 1;
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.stat-value {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
}

.stat-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.stat-change {
  font-size: 24rpx;
  font-weight: bold;
}

.stat-change.positive {
  color: #28a745;
}

.stat-change.negative {
  color: #dc3545;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.chart-section {
  margin-bottom: 30rpx;
}

.chart-container {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.chart-placeholder {
  height: 200rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2rpx dashed #ddd;
  border-radius: 8rpx;
  margin-bottom: 30rpx;
}

.chart-text {
  font-size: 32rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.chart-desc {
  font-size: 24rpx;
  color: #999;
}

.trend-data {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.trend-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.trend-date {
  font-size: 24rpx;
  color: #666;
  min-width: 120rpx;
}

.trend-bar {
  height: 20rpx;
  background: linear-gradient(90deg, #007bff, #0056b3);
  border-radius: 10rpx;
  min-width: 20rpx;
}

.trend-value {
  font-size: 24rpx;
  color: #333;
  font-weight: bold;
  min-width: 100rpx;
}

.analytics-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.analytics-card {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.card-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.card-content {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.metric {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.metric-label {
  font-size: 24rpx;
  color: #666;
}

.metric-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #007bff;
}

.top-products {
  margin-bottom: 30rpx;
}

.product-list {
  background: white;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.product-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.product-item:last-child {
  border-bottom: none;
}

.product-rank {
  width: 60rpx;
  height: 60rpx;
  background-color: #007bff;
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: bold;
  margin-right: 20rpx;
}

.product-info {
  flex: 1;
}

.product-name {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.product-sales {
  font-size: 24rpx;
  color: #666;
}

.product-revenue {
  font-size: 28rpx;
  font-weight: bold;
  color: #007bff;
}

.user-analysis {
  margin-bottom: 30rpx;
}

.analysis-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.analysis-item {
  background: white;
  padding: 30rpx;
  border-radius: 12rpx;
  text-align: center;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.analysis-title {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.analysis-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #007bff;
}
</style>